import os
import csv
import time
import requests
import uuid

UUID = uuid.uuid1
WEIBOMAIN_PATH = "/var/jenkins_home/workspace/WeiboMain"
allOnLineFileName = "allonline_{UUID}.csv"
whiteList = ["图片"]
problemAB = []
url = 'http://abtest.client.weibo.cn/downloadAllOnlineData?token=nieyu2'
blackPathList = ['WBPlayerInternalExt']  # 不用扫描的黑名单
scanTimes = 0


def loadAB():
    leng = 1
    print('开始拉取全量开关...')
    while (leng == 1):
        response = requests.get(url)
        leng = len(list(response.iter_content(1024)))  # 下载区块数
        if (leng == 1):
            print('下载失败')  # 如果是1 就是空文件 重新下载
        else:
            print('下载完成')

    print('将文件写入本地{out_file} 文件中。{os.getcwd()}')
    allonline = []
    with open(allOnLineFileName, 'wb') as f:
        for chunk in response.iter_content(1024):  # 防止文件过大，以1024为单位一段段写入
            f.write(chunk)
    print('所有的全量开关已下载到本地')
    print('开始处理文件...')
    with open(allOnLineFileName, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f, delimiter='\t')
        for line in reader:
            value = line["试验名称"]
            # 如果白名单存在 则只扫描白名单内的业务组
            if len(whiteList) != 0:
                groupName = line["项目组"]
                if groupName not in whiteList:
                    continue
            # 过滤命名带android的开关
            if "android" in value:
                continue
            else:
                allonline.append(value)

    # 将处理完成的开关名 写到本地
    final_ABs_path = "final_ABs_{uuid}"
    with open(final_ABs_path, 'wb') as f:
        for chunk in response.iter_content(1024):  # 防止文件过大，以1024为单位一段段写入
            f.write(chunk)
    print("处理完成 将结果写到{out_file} 文件中。{os.getcwd()}")
    return allonline


def search(dirname, abNames):
    global scanTimes
    global problemAB
    filenames = os.listdir(dirname)
    for filename in filenames:
        if filename.startswith("."):
            continue
        if filename in blackPathList:
            continue
        fullFileName = os.path.join(dirname, filename)
        if os.path.isdir(fullFileName):
            search(fullFileName, abNames)
        else:
            if os.path.exists(fullFileName):
                ext = os.path.splitext(fullFileName)[-1]
                if ext == '.m' or ext == '.mm':
                    try:
                        with open(fullFileName, 'r', encoding='utf-8') as f:
                            # print("检索:", fullFileName)
                            scanTimes += 1
                            for line in f:
                                for abName in abNames:
                                    if abName in line and abName not in problemAB:
                                        problemAB.append(abName)
                                        print("😄找到未下开关:{} 文件名:{}".format(abName, fullFileName))
                                        break
                    except PermissionError:
                        print("error")
                        return False
    return True


def final():
    finalList = []
    with open(allOnLineFileName, 'r', encoding='utf-8') as f:
        reader = csv.reader(f, delimiter='\t')
        header = next(reader)
        finalList.append(header)
        for abNmae in problemAB:
            for li in reader:
                if abNmae in li:
                    finalList.append(li)
                    break

    out_file = "result.csv"
    with open(out_file, "w", encoding='utf-8') as out_csv:
        writer = csv.writer(out_csv)
        for row in finalList:
            writer.writerow(row)
        print(f"{len(finalList)} 条数据已写入到 {out_file} 文件中。{os.getcwd()}")


def scan(abNames):
    print('开始扫描开关...')
    startTime = time.time()
    success = search(WEIBOMAIN_PATH, abNames)
    endTime = time.time()
    if success:
        print('扫描成功')
        final()
    else:
        print('扫描失败')
    print('\n 总共检测了:{}个文件 扫描了:{}个开关 耗时:{}秒'.format(scanTimes, len(abNames), endTime-startTime))


if __name__ == '__main__':
    abNames = loadAB()
    scan(abNames)
